package com.hdmp.auth.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hdmp.auth.entity.SysPermissionEntity;
import com.hdmp.auth.entity.SysRolePermissionEntity;
import com.hdmp.auth.entity.SysUserEntity;
import com.hdmp.auth.mapper.SysPermissionMapper;
import com.hdmp.auth.mapper.SysRolePermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Author: Chenyc
 * @Date: 2019/5/25 15:25
 */
@Service
public class SysRolePermissionService extends ServiceImpl<SysRolePermissionMapper, SysRolePermissionEntity> {
    @Autowired
    SysUserRoleService userRoleService;

    @Autowired
    SysRolePermissionMapper rolePermissionMapper;

    @Autowired
    SysPermissionMapper sysPermissionMapper;

    public List<SysPermissionEntity> findPermissionEntityByUser(SysUserEntity userEntity) {
        List<Integer> roleDbids = userRoleService.findRoleDbidByUser(userEntity);
        roleDbids = roleDbids == null? Lists.newArrayList():roleDbids;
        if( roleDbids.size() ==0){
            roleDbids.add(-1);
        }
        List<SysPermissionEntity> permissionEntities=new ArrayList<>();
        if(userEntity.getSuperUser()){
            QueryWrapper ss=new QueryWrapper();
            permissionEntities=sysPermissionMapper.selectList(ss);
        }else{
            permissionEntities = rolePermissionMapper.queryPermissionByRole(roleDbids);
        }

        return permissionEntities == null? Lists.newArrayList():permissionEntities;


    }

    @Transactional
    public void saveRolePermission(SysRolePermissionEntity[] sysRolePermissionEntitys) {
        if(sysRolePermissionEntitys.length>0){
            Integer roleId = sysRolePermissionEntitys[0].getRoleDbid();
            Map<String, Object> columnMap = Maps.newHashMap();
            columnMap.put("role_dbid", roleId);
            removeByMap(columnMap);
            List<SysRolePermissionEntity> entitiesList = Arrays.asList(sysRolePermissionEntitys);
            saveOrUpdateBatch(entitiesList);

        }

    }
}